package com.fengmi.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengmi.sso.entity.SysUser;
import com.fengmi.sso.mapper.SysUserMapper;
import com.fengmi.sso.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengmi.utils.jwt.JwtUtils;
import com.fengmi.utils.jwt.RsaUtils;
import com.fengmi.vo.ResultVO;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zhuxm
 * @since 2022-03-11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public ResultVO login(SysUser sysUser) {

        if (sysUser == null) {
            return  new ResultVO(false,"非法参数");
        }

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",sysUser.getAccount());
        queryWrapper.eq("user_type",6);

        SysUser sysUserDB = this.baseMapper.selectOne(queryWrapper);
        if (sysUserDB == null) {

            return  new ResultVO(false,"用户名或者密码不正确");
        }

        //比较密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(!passwordEncoder.matches(sysUser.getPassword(),sysUserDB.getPassword())){

            return  new ResultVO(false,"用户名或者密码不正确");
        }


        sysUserDB.setPassword("******");

        //颁发jwt令牌
        try {
            String path = ResourceUtils.getFile("classpath:rsa.pri").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(path);
            String token = JwtUtils.generateTokenExpireInMinutes(sysUserDB, privateKey, 30);

            return new ResultVO(true,"success",token);
        } catch (Exception e) {
            return  new ResultVO(false,"用户名或者密码不正确");
        }

    }

    @Override
    public ResultVO verify(String token) {

        if(StringUtils.isEmpty(token)){
            return  new ResultVO(false,"非法参数");
        }


        try {
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
            Object infoFromToken = JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            return  new ResultVO(true,"有效令牌");
        } catch (Exception e) {
            e.printStackTrace();
            return  new ResultVO(false,"无效令牌");
        }

    }
}
